package com.lottery.controller.qiuqiu.lobbyController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lottery.controller.BaseController;
import com.lottery.dao.qiuqiu.lobbyDao.LotteryDao;
import com.lottery.dto.SimulationAward;
import com.lottery.entity.Lottery;
import com.lottery.initData.InitData;
import com.lottery.obtainData.ObtainDataUtils;
import com.lottery.obtainData.SscYesWinningFactory.BJSCWinResult;
import com.lottery.obtainData.SscYesWinningFactory.SscWinResult;
import com.lottery.service.qiuqiu.JedisClient;
import com.lottery.service.qiuqiu.lobbyService.LotteryDrawService;
import com.lottery.utils.DateUtil;
import com.lottery.utils.RandCodeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 模拟开奖数据，供测试时使用
 *
 * @author Administrator
 */
@CrossOrigin
@RestController
@RequestMapping("/test")
public class SimulationAwardController extends BaseController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private JedisClient jedisClient;

    @Resource
    private LotteryDrawService lotteryDrawService;

    @Resource
    private LotteryDao lotteryDao;

    //ssc模拟开奖接口
    @RequestMapping(value = "/public/sscTestData", produces = "application/json;charset=utf-8", method = RequestMethod.GET)
    public String sscTestData(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();
        List<Object> list = new ArrayList<Object>();
        logger.info("sscTestData={}*******************");
        try {
            SimulationAward simulationAward = new SimulationAward();
            String curFullPeoriod = ObtainDataUtils.getFullPeriod(new Date());
            Date peoriodDate = obtainTime(curFullPeoriod);
            String opentime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(peoriodDate);

            simulationAward.setExpect(curFullPeoriod);
            simulationAward.setOpentime(opentime);

            String opencode = "";
            for (int i = 0; i < 5; i++) {
                int ac = RandCodeUtil.getRandNum(0, 9);
                opencode = opencode + (ac + ",");
            }
            opencode = opencode.substring(0, opencode.length() - 1);
            simulationAward.setOpencode(opencode);
            list.add(simulationAward);
            map.put("data", list);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("*****sscTestData error******:", e);
        }
        return JSON.toJSONString(map, true);
    }


    //pc28开奖接口
    @RequestMapping(value = "/public/pc28TestData", produces = "application/json;charset=utf-8", method = RequestMethod.GET)
    public String pc28TestData(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<String, Object>();
        List<Object> list = new ArrayList<Object>();
        logger.info("sscTestData={}*******************");
        try {
            SimulationAward simulationAward = new SimulationAward();

            String opentime = "";
            String curTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            int hours = Integer.parseInt(curTime.substring(11, 13));
            int minite = Integer.parseInt(curTime.substring(14, 16));
            if (hours == 23 && minite >= 55) {
                opentime = DateUtil.getDateFromString(curTime, "yyyy-MM-dd", 10) + "09:05:00";
            } else if (hours >= 0 && hours < 9) {
                opentime = DateUtil.getFormatDate("yyyy-MM-dd") + " 09:05:00";
            } else {
                opentime = curTime.substring(0, 10);
                int delay = (minite % 5);
                minite = minite - delay;
                if (minite >= 60) {
                    hours++;
                    minite = minite % 60;
                }
                String time = String.format(" %02d:%02d:00", hours, minite);
                opentime = opentime + time;
            }
            simulationAward.setOpentime(opentime);

            String curFullPeoriod = jedisClient.incr("pc28TestExpect") + "";
            simulationAward.setExpect(curFullPeoriod);

            String opencode = "";
            for (int i = 0; i < 20; i++) {
                int ac = RandCodeUtil.getRandNum(0, 99);
                String code = String.format("%02d", ac);
                opencode = opencode + (code + ",");
            }
            opencode = opencode.substring(0, opencode.length() - 1);
            opencode = opencode + "+" + RandCodeUtil.getRandNum(0, 99);
            simulationAward.setOpencode(opencode);
            list.add(simulationAward);
            map.put("data", list);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("*****pc28TestData error******:", e);
        }
        return JSON.toJSONString(map, true);
    }

    @RequestMapping(value = "/public/BJSCTestData", method = RequestMethod.GET, produces = {
            "application/json;charset=UTF-8"})
    public String BJSCTestData() {
        Map<String, Object> result = new HashMap<>();
        SimulationAward si = new SimulationAward();
        List<Object> list = new ArrayList<Object>();
        try {
            //检验时间
            Date date = new Date();
            int hours = date.getHours();
            int minutes = date.getMinutes();
            String nowTime = DateUtil.getFormatDate(date, "YYYY-MM-dd HH:mm:ss");
            //9点07分开奖,初始化jedis opentime
            String opentime = jedisClient.get("bjscOpentime");
            String opencode = jedisClient.get("bjscOpencode");
            Lottery lottery = lotteryDao.selectExpectYesterday();
            String expect = "";
            if (lottery == null) {
                expect = "20000";
            } else {
                expect = lottery.getExpect();
            }

            if (hours == 9 && minutes == 7) {
                String firstOpentime = DateUtil.getFormatDate("YYYY-MM-dd") + " 09:07:00";
                if (opentime == null) {
                    jedisClient.set("bjscOpentime", firstOpentime);
                    opentime = firstOpentime;
                } else {
                    if (!opentime.substring(0, 10).equals(DateUtil.getFormatDate("YYYY-MM-dd"))) {
                        jedisClient.set("bjscOpentime", firstOpentime);
                        opentime = firstOpentime;
                    }
                }

                //初始化开奖期号
                if (expect == null) {
                    jedisClient.set("bjscExpect", "20000");
                    expect = "20000";
                }
            }
            //获取开奖时间
            int nowMinute = (hours - 9) * 60 + minutes - 7;//当前时间据每天第一期开奖时间的分钟差
            int endMinute = (23 - 9) * 60 + 50;
            if (0 < nowMinute && nowMinute <= endMinute) {
                //开奖
                int num = nowMinute / 5;
                String expectStr = (Integer.parseInt(expect) + num) + "";
                if (nowMinute % 5 == 0 && !(expect.equals(expectStr))) {
                    //开奖时间
                    opentime = nowTime;
                    //开奖期号
                    expect = expectStr;
                    //开奖号码
                    opencode = getOpencode(opencode);
                } else {
                    expect = jedisClient.get("bjscExpect");
                }
                si.setExpect(expect);
                si.setOpentime(opentime);
                si.setOpencode(opencode);
                list.add(si);
                result.put("data", list);
            }
        } catch (Exception e) {
            logger.error(" searchWealthInfo error,{}", e);
        }
        return JSON.toJSONString(result, true);
    }

    private String getOpencode(String opencode) {
        LinkedList<String> list = new LinkedList<>();
        list.add("01");
        list.add("02");
        list.add("03");
        list.add("04");
        list.add("05");
        list.add("06");
        list.add("07");
        list.add("08");
        list.add("09");
        list.add("10");

        opencode = "";
        for (int i = 0; i < 9; i++) {
            int randNum = RandCodeUtil.getRandNum(0, list.size() - 1);
            String zz = list.get(randNum);
            opencode += zz + ",";
            list.remove(zz);
        }
        opencode += list.get(0);
        return opencode;
    }


    // 开奖时间的获得
    private Date obtainTime(String expect) {
        // 开奖的时间
        String formatDate = expect.substring(0, 4) + "-" + expect.substring(4, 6) + "-" + expect.substring(6, 8);
        String formatMorning = formatDate + " 00:00:00";
        String formatForenoon = formatDate + " 10:00:00";
        String formatEvening = formatDate + " 22:00:00";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long timeMorning = 0;
        long timeForenoon = 0;
        long timeEvening = 0;
        long timeNow = 0;
        try {
            timeMorning = simpleDateFormat.parse(formatMorning).getTime();
            timeForenoon = simpleDateFormat.parse(formatForenoon).getTime();
            timeEvening = simpleDateFormat.parse(formatEvening).getTime();
        } catch (ParseException e) {
            logger.error("*****obtainTime error******:", e);
        }
        Long NextExpectNumber = Long.valueOf(expect.substring(8, 11));
        if (NextExpectNumber >= 1 && NextExpectNumber <= 23) {
            timeNow = timeMorning + 300000 * NextExpectNumber;
        }
        if (NextExpectNumber >= 24 && NextExpectNumber <= 96) {
            timeNow = timeForenoon + 600000 * (NextExpectNumber - 24);
        }
        if (NextExpectNumber >= 97 && NextExpectNumber <= 120) {
            timeNow = timeEvening + 300000 * (NextExpectNumber - 96);
        }
        Date date = new Date(timeNow);
        logger.info("开奖的时间={}", date);
        return date;
    }

    @RequestMapping(value = "/public/test", method = RequestMethod.POST)
    public String test(HttpServletRequest request) {
        String msg = null;
        try {
            JSONObject jObject = new JSONObject();
            String body = "";

            body = readHttpBody(request);
            JSONObject obj = JSONObject.parseObject(body);
            String code = obj.getString("opencode");
            String opencode = "";
            int lotteyType = obj.getInteger("lotteyType");
            String expect = obj.getString("expect");

            for (int i = 0; i < code.length(); i++) {
                if (i < (code.length() - 1)) {
                    opencode += code.substring(i, i + 1) + ",";
                } else {
                    opencode += code.substring(i, i + 1);
                }
            }
            if (lotteyType == 1) {
                InitData.SSC_WINRESULT_MAP.clear();
                SscWinResult ssc = new SscWinResult();
                ssc.init(opencode);
                lotteryDrawService.sscYesWinningFactory(opencode, expect, lotteyType);
            }
            if (lotteyType == 3) {
                InitData.SSC_WINRESULT_MAP.clear();
                BJSCWinResult bjsc = new BJSCWinResult();
                String replace = opencode.replace("0", "10");
                bjsc.init(replace);
                lotteryDrawService.bjscYesWinningFactory(replace, expect, lotteyType);
            }
            msg = "开奖success";
        } catch (IOException e) {
            e.printStackTrace();
            msg = "开奖fail";
        }
        return msg;
    }
}
